package com.glacier.framework.boot.rest.response;

import com.glacier.framework.component.dto.response.Response;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * date 2023-12-29 11:25
 * 拦截controller返回值，封装后统一返回格式
 *
 * @author glacier
 * @version 1.0
 */
@Slf4j
@RestControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice<Object> {
    private final ObjectToJsonStringMapper objectToJsonStringMapper;

    public ResponseAdvice(ObjectToJsonStringMapper objectToJsonStringMapper) {
        this.objectToJsonStringMapper = objectToJsonStringMapper;
    }

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        log.info("返回值类型：{}, converterType: {}", returnType, converterType);
        return true;
    }

    @SneakyThrows
    @Override
    public Object beforeBodyWrite(
            Object body, MethodParameter returnType, MediaType selectedContentType,
            Class<? extends HttpMessageConverter<?>> selectedConverterType,
            ServerHttpRequest request, ServerHttpResponse response) {
        // 如果返回值为空，直接返回
        if (body == null) {
            return null;
        }
        // 如果Controller返回String的话，SpringBoot不会帮我们自动封装而直接返回，因此我们需要手动转换成json。
        if (body instanceof String) {
            return objectToJsonStringMapper.toJsonString(Response.success(body));
        }
        // 防止重复包裹的问题出现
        if (body instanceof Response) {
            return body;
        }
        return Response.success(body);
    }
}
